# ------------------------------------------------------------------------------------------------
### Generate Figure 10: Effects on vote share and turnout by party
# ------------------------------------------------------------------------------------------------

# Load data
load("../data/results/sdid_results.Rda")

# Define party order for consistent plotting
party_order <- c("The Left (Lewica)", "Polish Coalition (KP)", "Civic Coalition (KO)", "Law and Justice (PiS)")

# Filter and prepare data 
plot_data <- sdid_results %>%
  filter(
    # Filter for main analysis (Any Level, Any Type, notyettreated, Full Sample)
    sum_level == "Any Level" & 
    sum_type == "Any Type" & 
    level == "Any Level" & 
    type == "Any Type" & 
    control_sample == "notyettreated" & 
    no300k_sample == "Full Sample" & 
    noproposed_sample == "Full Sample",
    # Filter for specific parties and outcomes
    !(party %in% c("Opposition", "Overall Turnout")),
    outcome %in% c("Party Turnout", "Vote Share")
  ) %>%
  mutate(
    party = factor(party, levels = party_order),
    agg_outcome = factor(outcome, levels = c("Party Turnout", "Vote Share"))
  )

# Generate plot
ggplot(plot_data, aes(x = estimate, y = party, color = sample)) +
  # Confidence intervals (99%, 95%, 90%) with decreasing linewidth
  geom_errorbarh(aes(xmin = lower_cb_99, xmax = upper_cb_99), height = 0, linewidth = 1, alpha = 0.5, position = position_dodge(0.3)) +
  geom_errorbarh(aes(xmin = lower_cb_95, xmax = upper_cb_95), height = 0, linewidth = 3, alpha = 0.3, position = position_dodge(0.3)) +
  geom_errorbarh(aes(xmin = lower_cb_90, xmax = upper_cb_90), height = 0, linewidth = 5, position = position_dodge(0.3)) +
  # Point estimates
  geom_point(shape = 21, fill = "white", size = 3, stroke = 1.5, position = position_dodge(0.3)) +
  # Styling
  scale_color_manual(values = c("Full Sample" = "black", "< 50km Sample" = "grey"), guide = guide_legend(title = NULL)) +
  facet_wrap(~outcome) +
  xlim(-3, 3) +
  labs(x = "Percentage points") +
  geom_vline(xintercept = 0, linetype = "dotted") +
  theme_bw() +
  theme(
    legend.position = "bottom", 
    axis.title.y = element_blank(), 
    panel.grid.major.y = element_blank(), 
    text = element_text(size = 23)
  )

# Save the plot
ggsave("../output/plots/figure10.pdf", width = 14, height = 7, dpi = 700)